<?php

use core\lib\Exception as MyException;

/**
 * 公用函数
 */

function error($msg = '未知错误', $code = 404)
{
    // dd(new \core\lib\Exception(['code'=>1,'msg'=>'aa']));
    throw new MyException([
        'msg' => $msg,
        'code' => $code,
    ]);
}

function post($name = '', $default = '')
{
    $date = core\lib\Request::instance()->post($name);
    if ($date == "") {
        $date = $default;
    }
    return $date;
}

function get($name = '', $default = '')
{
    $date = core\lib\Request::instance()->get($name);
    if ($date == "") {
        $date = $default;
    }
    return $date;
}

/**
 * 获取日志操作类
 * 用法-1.logger()->error(string|array $content,array $extras);
 * 用法-2.logger()->info(string|array $content,array $extras);
 * 用法-3.logger()->warn(string|array $content,array $extras);
 */
if (!function_exists('logger')) {
    function logger(string $group = 'tool')
    {
        \core\lib\Logger::setConfig([$group => ['log_file' => $group . '.log']]);
        return \core\lib\Logger::getLogger($group);
    }
}

/**
 * 重新格式化数组
 */
function reformArr($arr = [], $field = '')
{
    $new_arr = [];
    if (!is_array($arr) || empty($arr) || $field == '') {
        return $new_arr;
    }
    foreach ($arr as $av) {
        if (!is_array($av)) {
            break;
        }
        $fields = explode('.', $field);
        $tmp = $av;
        foreach ($fields as $f) {
            if (!array_key_exists($f, $tmp)) {
                break;
            }
            $tmp = $tmp[$f];
        }
        if (!isset($new_arr[$tmp])) {
            $new_arr[(string)$tmp] = $av;
        }
    }
    return $new_arr;
}

/**
 * 输出多个参数
 */
function dd(...$vars)
{
    if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
        header('HTTP/1.1 500 Internal Server Error');
    }
    foreach ($vars as $v) {
        var_dump($v);
    }
    exit(1);
}

if (!function_exists('env')) {
    /**
     * 允许用户从环境中检索值已设置的变量。特别适用于检索的.env文件中设置的值在配置文件中使用。
     * @param string|null $default
     * @return bool|string|null
     */
    function env(string $key, $default = null)
    {
        $value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
        // 找不到？返回默认值
        if ($value === false) {
            return $default;
        }

        // 处理任何布尔值
        switch (strtolower($value)) {
            case 'true':
                return true;
            case 'false':
                return false;
            case 'empty':
                return '';
            case 'null':
                return null;
        }
        return $value;
    }
}

/**
 * 获取文件扩展名
 */
function getFileExt(string $filename)
{
    $arr = explode('.', $filename);
    return array_pop($arr);
}

/**
 * 对Spreadsheet对象进行下载
 */
function downloadExcel($excelObj, string $filename, string $format)
{
    ob_end_clean();
    // $format只能为 Xlsx 或 Xls
    $format = ucwords($format);
    if ($format == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    } elseif ($format == 'Xls') {
        header('Content-Type: application/vnd.ms-excel');
    }
    header("Content-Disposition: attachment;filename=" . $filename . '.' . strtolower($format));
    header('Cache-Control: max-age=0');
    header('Expires: 0');
    header('Cache-Control: private, no-transform, no-store, must-revalidate');
    header('Pragma: public');

    $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excelObj, $format);
    $objWriter->save('php://output');
    exit;
}

/**
 * 是否JSON数据
 */
if (!function_exists('isJson')) {
    function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }
}

/**
 * 给layui的特定结果
 */
if (!function_exists('layuiRet')) {
    function layuiRet(array $list, int $total, array $totalRow = [])
    {
        $res = [
            'code' => 0,
            'msg' => '获取成功',
            'count' => $total,
            'data' => $list,
            'totalRow' => $totalRow,
        ];
        exit(json_encode($res, JSON_UNESCAPED_UNICODE));
    }
}